package org.csu.demo.db.Controller;

import jakarta.servlet.http.HttpSession;
import org.csu.demo.db.domain.Course;
import org.csu.demo.db.domain.Teacher;
import org.csu.demo.db.service.CourseService;
import org.csu.demo.db.service.TeacherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Optional;

@Controller
public class CourseController {
    @Autowired
    private CourseService courseService;
    @Autowired
    private TeacherService teacherService;

    @GetMapping("/courses/{coursename}")
    public String getCourseDetails(@PathVariable String coursename,
                                   @RequestParam String studentId,
                                   Model model,
                                   HttpSession session) {
        if (session.getAttribute("currentUser") == null) {
            return "redirect:/login";
        }

        // 将studentId存入session以便后续使用
        session.setAttribute("currentStudentId", studentId);

        Optional<Course> courseOptional = courseService.getCourseByCoursename(coursename);
        if (!courseOptional.isPresent()) {
            return "redirect:/scores/" + studentId + "?error=课程不存在: " + coursename;
        }

        Course course = courseOptional.get();
        model.addAttribute("course", course);

        Optional<Teacher> teacherOptional = teacherService.getTeacherByName(course.getLecture());
        teacherOptional.ifPresent(teacher -> model.addAttribute("teacher", teacher));

        return "courseDetails";
    }
}